package contacts;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.JFileChooser;

import ezvcard.VCard;
import ezvcard.parameters.TelephoneTypeParameter;
import ezvcard.types.AddressType;
import ezvcard.types.BirthdayType;
import ezvcard.types.EmailType;
import ezvcard.types.FormattedNameType;
import ezvcard.types.StructuredNameType;

/**
 * Klasse welche eine Zugriffsmoeglichkeit auf alle Adressbuecher schaffen soll
 * 
 * @author Michi
 * 
 */
public class Books {

	/**
	 * Member Data
	 */
	LinkedList<Adressbuch> books;

	/**
	 * Konstruktor
	 */
	public Books() {

		books = new LinkedList<Adressbuch>();
	}

	public void addBook(Adressbuch ab) {
		books.add(ab);
	}

	public void deleteBook(Adressbuch ab) {
		books.remove(ab);
	}

	public Adressbuch getBook(int i) {
		return books.get(i);
	}

	/**
	 * Exportiert alle Personen eines Adressbuches als vCard
	 * 
	 * @param ab
	 *            Adressbuch welches exportiert werden soll
	 */

	public void exportAdressbook(Adressbuch ab) {

		for (int k = 0; k < ab.getSize(); k++) {
			Person x = ab.getPerson(k);

			String str = "";
			VCard export = new VCard();

			// Name section
			StructuredNameType name = new StructuredNameType();
			name.setFamily(x.getName());
			name.setGiven(x.getVorname());
			export.setStructuredName(name);
			//
			FormattedNameType fn = new FormattedNameType();
			fn.setValue(x.getFullname());
			export.addFormattedName(fn);

			// Adress section
			AddressType address = new AddressType();
			address.setPostalCode(x.getZip());
			address.setStreetAddress(x.getStreet());
			address.setLocality(x.getCity());
			export.addAddress(address);

			// mail section
			EmailType email = new EmailType();
			email.setValue(x.getEmail());
			export.addEmail(email);
			//
			// Telefon section
			if (x.getTelefonhome() != "") {
				export.addTelephoneNumber(x.getTelefonhome(),
						TelephoneTypeParameter.HOME);
			}

			if (x.getTelefonarbeit() != "") {
				export.addTelephoneNumber(x.getTelefonarbeit(),
						TelephoneTypeParameter.WORK);
			}

			if (x.getHandynummer() != "") {
				export.addTelephoneNumber(x.getHandynummer(),
						TelephoneTypeParameter.CELL);
			}

			if (x.getFax() != "") {
				export.addTelephoneNumber(x.getFax(),
						TelephoneTypeParameter.FAX);
			}

			// Birthday section
			if (x.getBirthday() != null) {
				// export.setBirthday(new BirthdayType(x.getBirthday()));
				export.setBirthday(new BirthdayType(StringToDate(x
						.getBirthday())));
			}

			str = export.write();

			File pathFile;
			String savePath = "";
			Writer fw = null;

			JFileChooser chooser = new JFileChooser();
			chooser.setCurrentDirectory(new java.io.File("user.home"));
			chooser.setDialogTitle("Speichern unter..");
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			chooser.setAcceptAllFileFilterUsed(false);

			if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
				pathFile = chooser.getSelectedFile();
				savePath = pathFile.getAbsolutePath();
				System.out.println(savePath);

			} else {
				System.out.println("No Selection ");
			}

			try {
				fw = new FileWriter(savePath + "/" + x.getVorname() + " "
						+ x.getName() + ".vcf");
				fw.write(str);
			} catch (IOException e) {
				System.err.println("Konnte Datei nicht erstellen");
			} finally {
				if (fw != null)
					try {
						fw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}

		}
	}

	/**
	 * Wandelt Datum in einen String
	 * 
	 * @param date
	 *            Datum dass gewandelt werden soll
	 * @return String des Datums
	 */
	@SuppressWarnings("deprecation")
	public String DateToString(Date date) {
		String str = "";
		String a = "";
		if (date.getDate() < 10) {
			a = "0" + date.getDate();
		} else {
			a = "" + date.getDate();
		}

		String b = "";
		if (date.getDate() < 9) {
			String s = (date.getMonth() + 1) + "";
			b = ("0" + s);
		} else {
			b = (date.getMonth() + 1) + "";
		}

		String c = (date.getYear() + 1900) + "";

		str = c + "-" + b + "-" + a;

		return str;

	}

	/**
	 * Wandelt String in Datum um
	 * 
	 * @param Date
	 *            String der gewandelt werden soll
	 * @return Datum des Strings
	 */
	public Date StringToDate(String Date) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date ret;
		try {
			ret = sdf.parse(Date);
			return ret;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}
}
